package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.lang.PatternPool;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbit.common.utils.SingUtil;
import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.object.pojo.InvoiceRecord;
import com.tbit.uqbike.object.pojo.vo.InvoiceRecordVO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.InvoiceRecordService;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelWrapper;
import com.tbit.utils.DateTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import java.util.*;

/**
 * 开票管理
 *
 * @author yee_
 * @version 1.0
 * @date 2023/8/7 14:28
 */
@RestController
@RequestMapping("/invoice")
public class InvoiceRecordController {


    @Resource
    private InvoiceRecordService invoiceRecordService;

    /**
     * 开票管理分页
     *
     * @param phone     手机号
     * @param email     邮箱
     * @param status    状态 0-已申请,待开票 1-已开票 2-已驳回 3-重开待审核 4-已退票
     * @param startTime 开始时间-传时间戳(以申请时间查)
     * @param endTime   结束时间-传时间戳(以申请时间查)
     * @param brandId   品牌id(必传)
     * @param page      页码(不传默认1)
     * @param size      每页显示记录条数(不传默认10)
     * @return 查询结果
     */
    @GetMapping("/listPage")
    public PageResult<InvoiceRecord> listPage(String phone, String email, Integer status, Long startTime, Long endTime,
                                              @RequestParam Integer brandId, String flowId,
                                              @RequestParam(required = false, defaultValue = "1") Integer page,
                                              @RequestParam(required = false, defaultValue = "10") Integer size
    ) {
        return invoiceRecordService.listPage(phone, email, status, startTime, endTime, brandId, flowId, page, size);
    }

    @GetMapping("/export")
    public void export(String phone, String email, Integer status, Long startTime, Long endTime, String flowId,
                       @RequestParam Integer brandId, HttpServletResponse response) {
        LambdaQueryWrapper<InvoiceRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.eq(InvoiceRecord::getUserPhone, phone);
        }
        if (Objects.nonNull(startTime) && Objects.nonNull(endTime)) {
            queryWrapper.ge(InvoiceRecord::getApplyTime, new Date(startTime));
            queryWrapper.le(InvoiceRecord::getApplyTime, new Date(endTime));
        }
        if (StringUtils.isNotBlank(flowId)) {
            queryWrapper.eq(InvoiceRecord::getFlowId, flowId);
        }
        if (StringUtils.isNotBlank(email)) {
            queryWrapper.like(InvoiceRecord::getEmail, email);
        }
        if (Objects.nonNull(status)) {
            queryWrapper.eq(InvoiceRecord::getStatus, status);
        }
        queryWrapper.eq(InvoiceRecord::getBrandId, brandId);
        queryWrapper.orderBy(true, false, InvoiceRecord::getId);
        List<InvoiceRecord> recodeList = invoiceRecordService.list(queryWrapper);
        List<String[]> dataList = new ArrayList<>();
        dataList.add(new String[]{"申请编号", "用户手机号", "用户邮箱", "用户申请时间", "发票抬头", "发票税号", "申请开票金额(元)", "状态"});
        recodeList.forEach(x -> dataList.add(new String[]{x.getFlowId(), x.getUserPhone(), x.getEmail(),
                DateTimeUtil.DateTimeToString(x.getApplyTime()), x.getCompanyTitle(), x.getCompanyTaxNumber(), x.getInvoiceAmount().toString(),
                transStatus(x.getStatus())
        }));
        String fileName = "发票记录导出" + DateTimeUtil.getNowTimeYMD();
        ExportExcelWrapper<String[]> export = new ExportExcelWrapper<>();
        export.exportExcel(fileName, fileName, null, dataList, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    private String transStatus(Integer status) {
        switch (status) {
            case 0:
                return "待开票";
            case 1:
                return "已开票";
            case 2:
                return "已驳回";
            case 3:
                return "重开待审核";
            case 4:
                return "已废弃";
            default:
                return "未知";
        }
    }

    /**
     * 开票详情
     *
     * @param invoiceId 开票记录id
     * @return 开票详情
     */
    @GetMapping("/detail/{invoiceId}")
    public Result<InvoiceRecordVO> detail(@PathVariable("invoiceId") Integer invoiceId) {
        return invoiceRecordService.detail(invoiceId);
    }

    /**
     * 发票审核处理
     *
     * @param invoiceId     开票记录id(必填)
     * @param auditStatus   审核状态(必填;传入1或0)  1-通过  2-驳回
     * @param invoiceNumber 发票单号 审核状态通过时必传；
     * @param file          pdf发票文件 审核状态通过时必传；
     * @param remark        备注
     * @return 接口处理结果
     */
    @PostMapping("/audit")
    public Result<String> audit(Integer invoiceId, Boolean auditStatus, String invoiceNumber,
                                MultipartFile file, String remark) {
        if (Objects.isNull(invoiceId)) {
            return Result.error("请选择申请记录");
        }
        if (Objects.isNull(auditStatus)) {
            return Result.error("请选择审核状态");
        }
        if (Boolean.TRUE.equals(auditStatus)) {
            if (Objects.isNull(invoiceNumber)) {
                return Result.error("请填写发票单号");
            }
            if (Objects.isNull(file)) {
                return Result.error("请上传发票凭证");
            }
            String fileSuffix = Optional.ofNullable(file.getOriginalFilename())
                    .filter(StringUtils::isNotBlank)
                    .filter(x -> x.lastIndexOf(".") != -1)
                    .map(x -> x.substring(x.lastIndexOf(".") + 1))
                    .orElse(null);
            String onlyPdfSuffix = "pdf";
            if (!onlyPdfSuffix.equalsIgnoreCase(fileSuffix)) {
                return Result.error("请上传pdf文件");
            }
        }
        return invoiceRecordService.audit(invoiceId, auditStatus, invoiceNumber, file, remark);
    }

    @GetMapping("/query/{orderNo}")
    public Result<Boolean> queryOrderHasBeenInvoicedByOrderNo(@PathVariable String orderNo) {
        return invoiceRecordService.queryOrderHasBeenInvoicedByOrderNo(orderNo);
    }

    /**
     * 重开待审核处理接口
     *
     * @param invoiceId   开票记录id(必填)
     * @param auditStatus 审核状态(必填;传入1或0) 1-通过 2-驳回
     * @return 处理结果
     */
    @PostMapping("/discard")
    public Result<String> discard(@FormParam("invoiceId") Integer invoiceId, @FormParam("auditStatus") Boolean auditStatus) {
        if (Objects.isNull(invoiceId)) {
            return Result.error("请选择申请记录");
        }
        if (Objects.isNull(auditStatus)) {
            return Result.error("请选择审核状态");
        }
        return invoiceRecordService.discard(invoiceId, auditStatus);
    }

    @PostMapping("/updateEmail")
    public Result<String> updateEmail(@FormParam("invoiceId") Integer invoiceId, @FormParam("email") String email) {
        if (Objects.isNull(invoiceId)) {
            return Result.error("请选择申请记录");
        }
        if (Objects.isNull(email)) {
            return Result.error("请输入邮箱");
        }
        if (!PatternPool.EMAIL.matcher(email).matches()) {
            return Result.error("邮箱地址不正确,请重新填写");
        }
        return invoiceRecordService.updateEmail(invoiceId, email);
    }

    /**
     * @description: 重新自动开票
     * @author: mo.shanyong
     * @date: 2025/5/30 10:14
     * @param: invoiceId
     * @return: com.tbit.common.entity.view.Result<java.lang.Object>
     */
    @PostMapping("/reAutoInvoicing")
    public Result<Object> reAutoInvoicing(Integer invoiceId){
        invoiceRecordService.reAutoInvoicing(invoiceId);
        return Result.success();
    }

}
